<template>
  <view class="hs-tab-002">
    <view
      class="menu-scroll"
      @touchstart="start"
      @touchend="end"
      @touchmove.stop="move"
    >
      <view
        class="hs-tab-item"
        v-for="(item, index) in tabItemList"
        :key="item.id"
        @click="clickTabItem(index)"
        :style="{
          width: tabsItemWidth + 'px',
          left: setTabItemLeft(index),
          transition: transition + 's',
        }"
      >
        <view class="layout-box" :class="index == magnifyIndex ? 'active' : ''">
          <view class="image-box">
            <image :src="item.imageUrl" mode="widthFix"></image>
            <view class="image-bottom-box">
              <image :src="item.imageUrl2"></image>
              <view class="title">{{ item.title }}</view>
              <view class="price">¥{{ item.price }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  onMounted,
  getCurrentInstance,
} from "vue";
import { weipinhuiData } from "@/common/simulatedData.js";
export default defineComponent({
  name: "hstab002",
  props: {},
  components: {},
  setup() {
    const data = reactive({
      tabItemList: JSON.parse(JSON.stringify(weipinhuiData)),
      scrollWidth: 0,
      tabsItemWidth: 0, //每一项的宽度
      initScrollLeft: 0, //初始的left
      showNum: 4, //和总数相关,建议是总数的3分之1
      startClientX: "",
      isLeftOrRight: "",
      moveLeft: 0, //移动的距离
      transition: 1.2,
      timer: null,
      moveNum: 1,
      startNumber: 2, //初始化前置的几个
      magnifyIndex: 0,
      isTouchmove: false,
    });
    onMounted(() => {
      data.magnifyIndex = data.startNumber + data.showNum / 2;
      getScrollinfo();
    });
    // 计算每个tab的left值
    const setTabItemLeft = (index) => {
      return (
        (index - data.startNumber) * data.tabsItemWidth -
        data.initScrollLeft +
        data.moveLeft +
        "px"
      );
    };

    const { proxy } = getCurrentInstance();
    const getScrollinfo = () => {
      const query = uni.createSelectorQuery().in(proxy);
      query
        .select(".menu-scroll")
        .boundingClientRect((ele) => {
          data.scrollWidth = ele.width;
          data.tabsItemWidth = ele.width / data.showNum;
          setTimeout(() => {
            data.initScrollLeft = data.tabsItemWidth / 2;
          }, 1000);
        })
        .exec(() => {
          autoPlayScroll();
        });
    };
    // 点击每个tab时
    const clickTabItem = (index) => {
      // 滑动不会触发点击事件
      // console.log("点击了", index);
      const moveLR = index - data.magnifyIndex;
      data.transition = 1.2;
      if (moveLR == 0) return;
      // 移动个数
      data.moveNum = Math.abs(moveLR);
      if (moveLR > 0) {
        data.isLeftOrRight = "left";
      } else if (moveLR < 0) {
        data.isLeftOrRight = "right";
      } else {
        data.isLeftOrRight = "";
      }
      isLeftOrRight();
    }; // 移动开始
    const start = (e) => {
      // console.log("滑动开始");
      data.startClientX = e.changedTouches[0].clientX;
      data.transition = 0;
      // 清除定时器
      clearInterval(data.timer);
    };
    //判断左右移动
    const isLeftOrRight = () => {
      if (data.isLeftOrRight == "left") {
        moveFirstToLast(data.tabItemList);
      } else if (data.isLeftOrRight == "right") {
        moveLastToFirst(data.tabItemList);
      }
    };
    // 移动结束
    const end = (e) => {
      // console.log("滑动结束");
      if (data.isTouchmove) {
        data.moveLeft = 0;
        isLeftOrRight();
        data.isLeftOrRight = "";
      }
      data.isTouchmove = false;
      // 开启自动轮播
      autoPlayScroll();
    };
    // 滑动时判断左右
    const move = (e) => {
      // console.log("滑动中");
      let touch = e.touches[0];
      let moveData = touch.clientX - data.startClientX;
      // 移动的距离是每个tab宽度的倍数上限
      data.moveLeft =
        moveData > 0
          ? Math.min(moveData, data.tabsItemWidth * data.startNumber)
          : Math.max(moveData, -data.tabsItemWidth * data.startNumber);
      // 计算滑动的个数
      data.moveNum = Math.abs(Math.round(moveData / data.tabsItemWidth));
      // moveNum最大为2
      const maxNum = data.showNum / 2;
      data.moveNum = data.moveNum > maxNum ? maxNum : data.moveNum;
      if (moveData > 0) {
        data.isLeftOrRight = "right";
      } else {
        data.isLeftOrRight = "left";
      }
      data.isTouchmove = true;
    };
    //自动轮播
    const autoPlayScroll = () => {
      data.transition = 1.2;
      data.moveNum = 1;

      data.timer = setInterval(() => {
        moveFirstToLast(data.tabItemList);
      }, 5000);
    };

    //  将数组前的n个元素移动到数组后
    const moveFirstToLast = (arr) => {
      const moveData = arr.splice(0, data.moveNum);
      arr.push(...moveData);
    };

    // 数组最后n个元素移动到数组最前面
    const moveLastToFirst = (arr) => {
      const moveData = arr.splice(-data.moveNum);
      arr.unshift(...moveData);
    };

    return {
      clickTabItem,
      setTabItemLeft,
      start,
      end,
      move,
      ...toRefs(data),
    };
  },
});
</script>

<style scoped lang="less">
@keyframes donghua {
  0% {
    transform: rotate(-10deg);
  }
  20% {
    transform: rotate(10deg);
  }
  30% {
    transform: rotate(-10deg) scale(1.3);
  }
  40% {
    transform: rotate(0deg) scale(1);
  }
  100% {
    transform: rotate(0deg) scale(1);
  }
}
.hs-tab-002 {
  padding: 40rpx 0;
  background: #fff;
  border-radius: 10rpx;
  background: url("/static/components/swiper/bg.webp");
  background-size: cover;
  overflow: hidden;
  padding-top: 100rpx;
  .menu-scroll {
    white-space: nowrap;
    width: 100%;
    height: 390rpx;
    box-sizing: border-box;
    position: relative;
    .hs-tab-item {
      display: inline-block;
      position: absolute;
      width: 150rpx;
      .layout-box {
        padding: 0 10rpx;
        transition: all 1.3s;
        &.active {
          // 缩放
          transform: scale(1.1);
        }
        .image-box {
          width: 100%;
          overflow: hidden;
          position: relative;
          image {
            width: 100%;
            display: block;
          }
          .image-bottom-box {
            display: flex;
            position: absolute;
            top: 48%;
            left: 50%;
            transform: translateX(-50%);
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            image {
              width: 140rpx;
              height: 140rpx;
              display: block;
              border-radius: 6rpx;
            }
            .title,
            .price {
              font-size: 20rpx;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              -webkit-box-orient: vertical;
              overflow: hidden;
              color: #000;
              text-align: center;
            }
            .price {
              font-weight: 700;
            }
          }
        }
      }
    }
  }
}
</style>
